package com.tgy.datastructure;

public class ArrayList<E> {
    private int size;
    private E[] array;
    private static int CAPACITY = 10;
    public ArrayList() {
        this(CAPACITY);
    }
    public ArrayList(int size) {
        if (size < 0) {
            size = CAPACITY;
        }
        this.array = (E[]) new Object[size];
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean contains(E o) {
        return indexOf(o) != -1;
    }

    public void add(E o) {
        expansionCap(size + 1);
        array[size++] = o;
    }

    public E get(int index) {
        checkRange(index);
        return array[index];
    }

    public E set(int index, E o) {
        checkRange(index);
        E value = array[index];
        array[index] = o;
        return value;
    }

    // 0 1 2 3 4 5
    public void add(int index, E o) {
        checkRangeForAdd(index);
        expansionCap(size + 1);
        // 最后一个元素往外挪动
        for (int i = size - 1; i >= index; i--) {
            array[i + 1] = array[i];
        }
        array[index] = o;
        size++;
    }

    public E remove(int index) {
        checkRange(index);
        E result = array[index];
        for (int i = index + 1; i < size; i++) {
            array[i - 1] = array[i];
        }
        array[size] = null;
        size--;
        return result;
    }

    public int indexOf(E o) {
        for (int i = 0; i < size; i++) {
            if (array[i].equals(o)) {
                return i;
            }
        }
        return -1;
    }

    public void clear(){

        for (int i = 0; i < size; i++) {
            array[i] = null;
        }
        size = 0;
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();
        sb.append("size = " + size + ", [");

        for (int i = 0; i < size; i++) {
            if (i > 0) {
                sb.append(", ");
            }
            sb.append(array[i]);
        }
        sb.append("]");
        return sb.toString();
    }

    private void expansionCap(int enSize){

        if (enSize <= array.length) {
            return;
        }
        int oldLen = array.length;
        int newLen = oldLen + (oldLen >> 1);

        E[] newArray = (E[]) new Object[newLen];
        for (int i = 0; i < size; i++) {
            newArray[i] = array[i];
        }
        array = newArray;
        System.out.println("扩容" + newLen);
    }

    private void checkRange(int index){
        if (index >= size) {
            throw new IndexOutOfBoundsException("index out of bounds");
        }
    }

    private void checkRangeForAdd(int index){
        if(index > size) {
            throw new IndexOutOfBoundsException("index out of bounds");
        }
    }

}
